package io.gitee.mingbaobaba.security.starter.utils;

import io.gitee.mingbaobaba.security.core.constants.ErrorCodeConstant;
import io.gitee.mingbaobaba.security.core.exception.SecurityBusinessException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;



/**
 * <p>servlet工具</p>
 *
 * @author yingsheng.ye
 * @version 1.0.0
 * @since 2023/8/29 9:36
 */
public class ServletUtil {

    private ServletUtil() {

    }

    /**
     * 获取当前会话的 request 对象
     *
     * @return request
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes == null) {
            throw new SecurityBusinessException(ErrorCodeConstant.CODE_NO_HTTP_SERVLET_REQUEST,
                    "根据上下文获取HttpServletRequest对象失败");
        }
        return servletRequestAttributes.getRequest();
    }

    /**
     * 获取当前会话的 response 对象
     *
     * @return response
     */
    public static HttpServletResponse getResponse() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes == null) {
            throw new SecurityBusinessException(ErrorCodeConstant.CODE_NO_HTTP_SERVLET_RESPONSE,
                    "根据上下文获取HttpServletResponse对象失败");
        }
        return servletRequestAttributes.getResponse();
    }

}
